package com.education.wisdom.controller;

import com.education.common.utils.ApiReturnObject;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.pojo.Catalog;
import com.education.wisdom.pojo.JrSchool;
import com.education.wisdom.pojo.JrSchoolCatalog;
import com.education.wisdom.pojo.UserCatalogBuy;
import com.education.wisdom.service.ICatalogService;
import com.education.wisdom.service.IJrSchoolCatalogService;
import com.education.wisdom.service.IJrSchoolService;
import com.education.wisdom.service.IUserCatalogBuyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 学校 信息操作处理
 *
 * @author d
 * @date 2020-08-10
 */
@RestController
@RequestMapping("/jrSchool")
public class JrSchoolController  {

    @Autowired
    private IJrSchoolService jrSchoolService;
    @Autowired
    private IJrSchoolCatalogService schoolCatalogService;
    @Autowired
    private ICatalogService catalogService;
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private IUserCatalogBuyService userCatalogBuyService;


    @GetMapping("/fingById")
    public String findById(@RequestParam("id") Integer id){
        JrSchool jrSchool = jrSchoolService.selectJrSchoolById(id);
        if (jrSchool == null){
            return "暂无学校";
        }
        return jrSchool.getSchoolName();
    }


    /** 根据子级查询上级 并添加值下级 */
    public List<Catalog> findParentBySon(List<Catalog> catalogs){
        //章列表
        HashMap<Integer, Catalog> map = Maps.newHashMap();
        ArrayList<Catalog> list = Lists.newArrayList();
        for (Catalog catalog : catalogs) {
            int i = 0;
            //父级id重复 不用进行查询添加 将该课程添加至对应父级课程下
            if(map.containsKey(catalog.getParentId())){
                Catalog catalog1 = map.get(catalog.getParentId());
                //将节添加值章节下
                List<Catalog> children = catalog1.getChildren() == null ? Lists.newArrayList() : catalog1.getChildren() ;
                children.add(catalog);
                catalog1.setChildren(children);
                //根据键 覆盖掉之前的值
                map.put(catalog.getParentId(),catalog1);
            }else {
                //章
                Catalog catalog2 = catalogService.selectCatalogByCatalogId(catalog.getParentId());
                List<Catalog> children = catalog2.getChildren() == null ? Lists.newArrayList() : catalog2.getChildren();
                children.add(catalog);
                catalog2.setChildren(children);
                //map 键 parentId 值 对象
                map.put(catalog.getParentId(),catalog2);
            }
        }
        list.addAll(map.values());
        return list;
    }




    /** 已购买资源 查询父级目录  节 章 分类 */
    @GetMapping("/buyCatalogList")
    public ApiReturnObject buyCatalogList(Integer id){
        //已购买节列表
        List<Catalog> catalogs = catalogService.selectCatalogBySchoolId(id);
        if(catalogs.size() > 0){
            List<Catalog> parentBySon = findParentBySon(catalogs);
            List<Catalog> parentBySon1 = findParentBySon(parentBySon);
           /* //章列表
            HashMap<Integer, Catalog> map = Maps.newHashMap();
            ArrayList<Catalog> list = Lists.newArrayList();
            for (Catalog catalog : catalogs) {
                int i = 0;
                //父级id重复 不用进行查询添加 将该课程添加至对应父级课程下
                if(map.containsKey(catalog.getParentId())){
                    Catalog catalog1 = map.get(catalog.getParentId());
                    //将节添加值章节下
                    List<Catalog> children = catalog1.getChildren() == null ? Lists.newArrayList() : catalog1.getChildren() ;
                    children.add(catalog);
                    catalog1.setChildren(children);
                    //根据键 覆盖掉之前的值
                    map.put(catalog.getParentId(),catalog1);
                }else {
                    //章
                    Catalog catalog2 = catalogService.selectCatalogByCatalogId(catalog.getParentId());
                    List<Catalog> children = catalog2.getChildren() == null ? Lists.newArrayList() : catalog2.getChildren();
                    children.add(catalog);
                    catalog2.setChildren(children);
                    //map 键 parentId 值 对象
                    map.put(catalog.getParentId(),catalog2);
                }
            }*/
            return new ApiReturnObject("200","查询成功",parentBySon1);
        }
        return new ApiReturnObject("201","该学校暂无购买课程","");
    }



    /** 购买时目录列表 */
    @GetMapping("/catalogList")
    public ApiReturnObject catalogList(Integer id){
        //第一级
        List<Catalog> catalogs = catalogService.selectByParentId2(0);
        ArrayList<Integer> list1 = Lists.newArrayList();
        for (int x = 0; x < catalogs.size(); x++) {
            Catalog catalog = catalogs.get(x);
            //章
            List<Catalog> catalogs1 = catalogService.selectByParentId2(catalog.getCatalogId());
            ArrayList<Integer> list = Lists.newArrayList();
            for (int i = 0; i < catalogs1.size(); i++) {
                Catalog catalog1 = catalogs1.get(i);
                //节
                List<Catalog> catalogs2 = catalogService.selectByParentIdThree(catalog1.getCatalogId(),id);
                if(catalogs2.size() == 0){
                    //下面的节已经全部购买
                    list.add(i);
                }
                catalog1.setChildren(catalogs2);
            }
            if(list.size()>0){
                for (int i = 0; i < list.size(); i++) {
                    //将没有节的章节删除掉
                    catalogs1.remove(list.get(i) - i);
                }
            }
            if(catalogs1.size() == 0){
                list1.add(x);
            }
            catalog.setChildren(catalogs1);
        }
        if(list1.size() > 0){
            for (int i = 0; i < list1.size(); i++) {
                catalogs.remove(list1.get(i) - i);
            }
        }

        return new ApiReturnObject("200","查询成功",catalogs);
    }




    /** 格式化时间 */
    public String formatDate(Date date){
        //格式化创建时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }

    /**
     *  购买 往中间表中添加数据
     */
    @PostMapping("/buyCatalog")
    public ApiReturnObject buyCatalog(@RequestBody JrSchool school){
        //添加学校购买课程
        if(school.getCatalogIds().size() > 0){
            JrSchoolCatalog jrSchoolCatalog = new JrSchoolCatalog();
            jrSchoolCatalog.setSchoolId(school.getId());
            for (Integer catalogId : school.getCatalogIds()) {
                jrSchoolCatalog.setCatalogId(catalogId);
                schoolCatalogService.insertJrSchoolCatalog(jrSchoolCatalog);
                //开通课程后 该校所有老师都可以看
                List<Integer> list = userFeign.selectBySchooleId(school.getId());
                if (list.size() > 0) {
                    for (Integer usid : list) {
                        UserCatalogBuy userCatalogBuy = new UserCatalogBuy();
                        userCatalogBuy.setCatalogId(catalogId);
                        userCatalogBuy.setUserId(usid.toString());
                        userCatalogBuy.setDeflag("1");
                        userCatalogBuyService.insert(userCatalogBuy);
                    }
                }
            }
            return new ApiReturnObject("200","添加成功","");
        }
        return new ApiReturnObject("201","请选择购买课程","");
    }


    /**
     * 查询学校列表 以及购买课程父级名称
     */
    @GetMapping("/list")
    public ApiReturnObject list(JrSchool jrSchool,Integer pageNum,Integer pageSize) {
        if(pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum,pageSize);
        }
        List<JrSchool> list = jrSchoolService.selectJrSchoolList(jrSchool);
        //遍历学校 根据中间表 查询出已购买课程的id    根据id查询出具体课程名字
        for (JrSchool school : list) {
            String date = formatDate(school.getCreateTime());
            school.setTimeString(date);
            List<Integer> catalogIdList = schoolCatalogService.selectJrSchoolCatalogBySchoolId(school.getId());
            if(catalogIdList.size() > 0){
                //线下购买小节的专业名称
                List<String> nameList = catalogService.isBuyOffline(catalogIdList);
                StringBuilder buffer = new StringBuilder();
                //遍历进行拼接
                for (int i = 0; i < nameList.size(); i++) {
                    if(i == nameList.size() - 1){
                        //最后一个名字
                        buffer.append(nameList.get(i));
                    }else {
                        buffer.append(nameList.get(i)).append("、");
                    }
                }
                school.setNameString(buffer.toString());
            }else {
                school.setNameString("");
            }
        }
        PageInfo<JrSchool> pageInfo = new PageInfo<>(list);
        return new ApiReturnObject("200","查询成功",pageInfo);
    }


    /**
     * 新增保存学校 添加到智慧云的学校里面
     */
    @Transactional
    @PostMapping("/add")
    public ApiReturnObject addSave(@RequestBody JrSchool jrSchool) {
            jrSchool.setCreateTime(new Date());
            jrSchoolService.insertJrSchool(jrSchool);
            //拿到账号密码进行添加用户
            return new ApiReturnObject("200","新增成功","新增成功");
    }


    /**
     *  详情
     */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer id){
        JrSchool jrSchool = jrSchoolService.selectJrSchoolById(id);
        return new ApiReturnObject("200","查询成功",jrSchool);
    }


    /**
     * 修改保存学校
     */
    @Transactional
    @PostMapping("/update")
    public ApiReturnObject editSave(@RequestBody JrSchool jrSchool) {
        try {
//            //根据学校id 以及角色id 判断账号是否要改变
//            boolean b = userFeign.findUserBySchoolId(jrSchool.getId(),jrSchool.getSchoolPhone());
//            if(b){
//                //没修改账号，只修改密码
//                if(jrSchool.getPassword() != null && !"".equals(jrSchool.getPassword())){
//                    //根据手机号修改学校用户密码
//                    userFeign.updatePasswordByPhone(jrSchool.getSchoolPhone(),jrSchool.getPassword());
//                }
//            }else {
//                //重新添加用户
//                userFeign.addUser(jrSchool.getSchoolPhone(), jrSchool.getPassword(), jrSchool.getId());
//            }
            jrSchoolService.updateJrSchool(jrSchool);
            return new ApiReturnObject("200","修改成功","");
        }catch (Exception ignored){

        }
        return null;
    }

    /**
     * 删除学校
     */
    @PostMapping("/del")
    public ApiReturnObject remove(String ids) {
        jrSchoolService.deleteJrSchoolByIds(ids);
        return new ApiReturnObject("200","删除成功","");
    }


    @GetMapping("/selectAll")
    public ApiReturnObject selectAll(){
        List<JrSchool> jrSchools = jrSchoolService.selectJrSchoolList(null);
        return new ApiReturnObject("200","查询成功",jrSchools);
    }
}